package cn.stylefeng.guns.modular.fsjs.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import cn.stylefeng.guns.core.shiro.ShiroKit;
import cn.stylefeng.guns.core.util.ExcellUtil;
import cn.stylefeng.guns.core.util.ServerResponse;
import cn.stylefeng.guns.modular.system.model.Indenteruwy;
import cn.stylefeng.guns.modular.system.model.Midwater;
import cn.stylefeng.guns.modular.system.model.Swyreport;
import cn.stylefeng.guns.modular.system.model.Techchange;
import cn.stylefeng.guns.modular.system.model.User;
import cn.stylefeng.guns.modular.system.service.IUserService;
import cn.stylefeng.guns.modular.system.dao.BasemsgMapper;
import cn.stylefeng.guns.modular.system.dao.MidwaterMapper;
import cn.stylefeng.guns.modular.system.dao.SwyreportMapper;
import cn.stylefeng.guns.modular.fsjs.service.IMidwaterService;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author stylefeng
 * @since 2019-03-06
 */
@Service
public class MidwaterServiceImpl extends ServiceImpl<MidwaterMapper, Midwater> implements IMidwaterService {
	String mainPath="";
	@Autowired
	private MidwaterMapper midwaterMapper;
	@Autowired
    private IUserService userService;
	@Override
	@Transactional(propagation =Propagation.REQUIRED,rollbackFor=Exception.class,isolation = Isolation.READ_COMMITTED)
	public Object pushMsg(HttpServletRequest request, List<Midwater> midwaterLi) {
		SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    	User user = userService.selectById(ShiroKit.getUser().getId());
    	if(midwaterMapper.getIfComit(user)>0){
			return ServerResponse.createByErrorMessage("年报数据已经提交，无法修改");
		}
    	mainPath=request.getSession().getServletContext().getRealPath("/")+"\\static\\excell\\";
    	int point=0;
    	
    	for(int i=0;i<midwaterLi.size();i++){
			Midwater temp=midwaterLi.get(i);
			if(this.checkInput(temp, i)==false){
				return ServerResponse.createByErrorMessage("提交数据有误");
			}
    	}
    	
		for(int i=0;i<midwaterLi.size();i++){
			Midwater temp=midwaterLi.get(i);
			if(this.checkInput(temp, i)==true){
				temp.setAccount(user.getAccount());
				temp.setOperater(user.getAccount());
				temp.setVersion("2");
				temp.setTs(sf.format(new Date()));
			}else{
				continue;
			}
			if(i==0){
				midwaterMapper.delTempMsg(temp);
			}
			
			if(midwaterMapper.pushMsg(temp)==0){
				return ServerResponse.createByErrorMessage("保存数据库出错");
			}else if(i==0){
				point++;
			}
			
		}
//			this.delMsg(user);
			if(point>0){
				//初始化excell成功
				Midwater temp=midwaterLi.get(0);
				temp.setAccount(user.getAccount());
				ServerResponse cf=(ServerResponse)this.createFile(temp);
				if(cf.getCode()==200){
					//
					List<Midwater> bsg=this.getMsgByAccountExcell(temp);
					if(bsg.size()>0){
						if(bsg.size()>3){
							for(int j=0;j<bsg.size()-3;j++){
								ExcellUtil.insertRows(mainPath+temp.getAccount()+"_中水.xlsx", 12+j, 25, 16,10);
							}
						}
						ServerResponse sm=(ServerResponse)this.stuffMsg(bsg,user);
						if(sm.getCode()==200){
							ServerResponse fn=(ServerResponse)this.toPDF(temp);
							if(fn.getCode()==200){
								this.delMsg(user);
								return ServerResponse.createBySuccessMessage("保存成功");
							}else{
								return fn;
							}
						}else{
							return sm;
						}
						
					}else{
						return ServerResponse.createByErrorMessage("数据库不存在记录");
					}
					
				}else{
					return cf;
				}
				
			}else{
				return ServerResponse.createByErrorMessage("数据格式错误");
			}
		
	}

	public boolean checkInput(Midwater temp,int i){
		if(StringUtils.isNotBlank(temp.getPrjName())&&
				StringUtils.isNotBlank(temp.getWaterUnitName())&&
				StringUtils.isNotBlank(temp.getWaterUnitId())&&
				StringUtils.isNotBlank(temp.getDeviceStatus())&&
				StringUtils.isNotBlank(temp.getUnitHead())&&
				(
					"1".equals(temp.getFlushToilet())||
					"1".equals(temp.getGreen())||
					"1".equals(temp.getLandscape())||
					"1".equals(temp.getRoadSpray())||
					"1".equals(temp.getCarWash())||
					"1".equals(temp.getIndustry())||
					"1".equals(temp.getOtherUse())
					
				)){
				return true;
			}else{
				return false;
			}
	}
	
	@Override
	public List<Midwater> getMsgByAccount(User user) {
		return midwaterMapper.getMsgByAccount(user);
	}

	@Override
	public List<Map<String, String>> getHangyeCode() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Midwater> getMsgByAccountExcell(Midwater midwater) {
		
		/*File file=new File(mainPath+swyreport.getAccount()+"_用水单位基本信息.xlsx");
		 FileInputStream fis;
		try {
			fis = new FileInputStream(file);
			Workbook workbook= WorkbookFactory.create(fis);
			Sheet sheet=workbook.getSheetAt(0);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		return midwaterMapper.getMsgByAccountExcell(midwater);
	}

	
	
	private Object createFile(Midwater midwater){
		return ExcellUtil.copyFile(mainPath,midwater,"中水");
	}
	
	private Object stuffMsg(List<Midwater> midwaterLi,User user){
//		ExcellUtil.insertRows(mainPath+swyreport.getAccount()+"_中水.xlsx", 12,30,16);
		File file=new File(mainPath+midwaterLi.get(0).getAccount()+"_中水.xlsx");
		try {
		FileInputStream fis=new FileInputStream(file);
	     Workbook workbook= WorkbookFactory.create(fis);
	     Sheet sheet=workbook.getSheetAt(0);
	     int size=3;
	     if(midwaterLi.size()>3){
	    	 size=midwaterLi.size();
	     }
	   //填表单位名称
	     if(StringUtils.isNotBlank(user.getCompany())){
	    	 String oldValue=ExcellUtil.getExcellString(sheet,0,5);
	    	 oldValue=oldValue.replace(":", ":"+user.getCompany());
	    	 ExcellUtil.updateExcel(sheet,0,5,oldValue);
	     }
	   //年份
	     if(midwaterLi.get(0).getRecYear()!=null){
	    	 String oldValue=ExcellUtil.getExcellString(sheet,7,5);
	    	 oldValue=oldValue.replace("20  ", Integer.toString(midwaterLi.get(0).getRecYear()));
	    	 ExcellUtil.updateExcel(sheet,7,5,oldValue);
	     }
		//报出日期
		 if(StringUtils.isNotBlank(midwaterLi.get(0).getTs())){
			 String oldValue=ExcellUtil.getExcellString(sheet,11,9+size);
	    	 oldValue=oldValue.replace("20", midwaterLi.get(0).getTs().substring(0, 4));
	    	 oldValue=oldValue.replace("月", midwaterLi.get(0).getTs().substring(5, 7)+"月");
	    	 oldValue=oldValue.replace("日 ", midwaterLi.get(0).getTs().substring(8, 10)+"日");
			 ExcellUtil.updateExcel(sheet,11,9+size,oldValue);
		 }
		 //统计负责人： 
		 if(StringUtils.isNotBlank(midwaterLi.get(0).getUnitHead())){
			 String oldValue=ExcellUtil.getExcellString(sheet,0,9+size);
			 String preValue="";
			 for(int c=0;c<midwaterLi.get(0).getUnitHead().length();c++){
				 preValue=preValue+" ";
			 }
			 oldValue=oldValue.replace("单位负责人:"+preValue, "单位负责人: "+midwaterLi.get(0).getUnitHead());
			 ExcellUtil.updateExcel(sheet,0,9+size,oldValue);
		 }
		 //填表人
		 if(StringUtils.isNotBlank(midwaterLi.get(0).getOperater())){
			 String oldValue=ExcellUtil.getExcellString(sheet,4,9+size);
			 String preValue="";
			 for(int c=0;c<midwaterLi.get(0).getOperater().length();c++){
				 preValue=preValue+" ";
			 }
			 oldValue=oldValue.replace("填表人:"+preValue, "填表人:"+midwaterLi.get(0).getOperater());
			 ExcellUtil.updateExcel(sheet,4,9+size,oldValue);
		 }
		 //电话
		 if(StringUtils.isNotBlank(user.getPhone())){
			 String oldValue=ExcellUtil.getExcellString(sheet,7,9+size);
			 String preValue="";
			 for(int c=0;c<user.getPhone().length();c++){
				 preValue=preValue+" ";
			 }
			 oldValue=oldValue.replace("电话:"+preValue, "电话:"+user.getPhone());
			 ExcellUtil.updateExcel(sheet,7,9+size,oldValue);
		 }
		 
		for(int i=0;i<midwaterLi.size();i++){
			Midwater tmp=midwaterLi.get(i);
			//项目名称	
			if(StringUtils.isNotBlank(tmp.getPrjName())){
				ExcellUtil.updateExcel(sheet,0,9+i,tmp.getPrjName());
			}
			//用水户名	
			if(StringUtils.isNotBlank(tmp.getWaterUnitName())){
				ExcellUtil.updateExcel(sheet,1,9+i,tmp.getWaterUnitName());
			}
			//用水户编号	
			if(StringUtils.isNotBlank(tmp.getWaterUnitId())){
				ExcellUtil.updateExcel(sheet,2,9+i,tmp.getWaterUnitId());
			}
			//工程状态	
			if(StringUtils.isNotBlank(tmp.getDeviceStatus())){
				if("1".equals(tmp.getDeviceStatus())){
					ExcellUtil.updateExcel(sheet,3,9+i,"√");
				}else if("2".equals(tmp.getDeviceStatus())){
					ExcellUtil.updateExcel(sheet,4,9+i,"√");
				}else{
					ExcellUtil.updateExcel(sheet,5,9+i,"√");
				}
			}
			//年利用总量		
			if(tmp.getWaterVolumeYear()!=null){
				ExcellUtil.updateExcel(sheet,6,9+i,Double.toString(tmp.getWaterVolumeYear()));
			}
			//冲厕	
			if("1".equals(tmp.getFlushToilet())){
				ExcellUtil.updateExcel(sheet,7,9+i,"√");
			}
			//绿化	
			if("1".equals(tmp.getGreen())){
				ExcellUtil.updateExcel(sheet,8,9+i,"√");
			}
			//景观	
			if("1".equals(tmp.getLandscape())){
				ExcellUtil.updateExcel(sheet,9,9+i,"√");
			}
			//道路喷洒	
			if("1".equals(tmp.getRoadSpray())){
				ExcellUtil.updateExcel(sheet,10,9+i,"√");
			}
			//洗车	
			if("1".equals(tmp.getCarWash())){
				ExcellUtil.updateExcel(sheet,11,9+i,"√");
			}
			//工业	
			if("1".equals(tmp.getIndustry())){
				ExcellUtil.updateExcel(sheet,12,9+i,"√");
			}
			//其他	
			if("1".equals(tmp.getOtherUse())){
				ExcellUtil.updateExcel(sheet,13,9+i,"√");
			}
			//城市杂用水质监测报告	
			if("1".equals(tmp.getUsualDetected())){
				ExcellUtil.updateExcel(sheet,14,9+i,"√");
			}
			//景观环境水质监测报告	
			if("1".equals(tmp.getLandscapeDetected())){
				ExcellUtil.updateExcel(sheet,15,9+i,"√");
			}
		}
		fis.close();//关闭文件输入流
		 
	     FileOutputStream fos=new FileOutputStream(file);
	     workbook.write(fos);
	     fos.close();//关闭文件输出流
		 
		 return ServerResponse.createBySuccessMessage("填充数据成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ServerResponse.createBySuccessMessage("修改excell成功");
	}
	
	private Object toPDF(Midwater midwater){
		try {
			return ExcellUtil.excel2Pdf(mainPath,midwater,"中水");
		} catch (Exception e) {
			return ServerResponse.createByErrorMessage(e.getMessage());
		}
	}
	
	private void delMsg(User user){
		midwaterMapper.delMsg(user);
		midwaterMapper.updateVersion(user);
	}
	
	@Override
	public Object checkCommit(User user) {
		List<Midwater> midwaterLi=this.getMsgByAccount(user);
		if(midwaterLi.size()>0){
			
			for(int i=0;i<midwaterLi.size();i++){
				Midwater temp=midwaterLi.get(i);
				if(
						
						StringUtils.isBlank(temp.getPrjName())||
						StringUtils.isBlank(temp.getWaterUnitName())||
						StringUtils.isBlank(temp.getWaterUnitId())||
						StringUtils.isBlank(temp.getDeviceStatus())||
						StringUtils.isBlank(temp.getUnitHead())||
						(
								!"1".equals(temp.getFlushToilet())&&
								!"1".equals(temp.getGreen())&&
								!"1".equals(temp.getLandscape())&&
								!"1".equals(temp.getRoadSpray())&&
								!"1".equals(temp.getCarWash())&&
								!"1".equals(temp.getIndustry())&&
								!"1".equals(temp.getOtherUse())
								
								/*temp.getPrjName()==null||
				temp.getWaterUnitName()==null||
				temp.getWaterUnitId()==null||
				temp.getDeviceStatus()==null||
				temp.getWaterVolumeYear()==null||
				(
				temp.getFlushToilet()==null&&
				temp.getGreen()==null&&
				temp.getLandscape()==null&&
				temp.getRoadSpray()==null&&
				temp.getCarWash()==null&&
				temp.getIndustry()==null&&
				temp.getOtherUse()==null*/
								
								)
						){
					return ServerResponse.createByErrorMessage("中水内容尚未填写完成");
				}
			}
			return ServerResponse.createBySuccessMessage("中水内容填写完成");
		}else{
			return ServerResponse.createByErrorMessage("中水内容尚未填写完成");
		}
	}
	
	@Override
	public int getIfComit(User user) {
		return midwaterMapper.getIfComit(user);
	}

	@Override
	public int updateComit() {
		return midwaterMapper.updateComit();
	}

	@Override
	public Object bulidEmptyFile(String path, Midwater midwater, User user) {
		mainPath=path;
		List<Midwater> temp=new ArrayList<Midwater>();
		temp.add(midwater);
		//初始化excell成功
		ServerResponse cf=(ServerResponse)this.createFile(midwater);
		if(cf.getCode()==200){
			//
			ServerResponse sm=(ServerResponse)this.stuffMsg(temp,user);
			if(sm.getCode()==200){
				ServerResponse fn=(ServerResponse)this.toPDF(midwater);
					if(fn.getCode()==200){
						return ServerResponse.createBySuccessMessage("保存成功");
					}else{
						return fn;
					}
			}else{
				return sm;
			}
			
			}else{
				return ServerResponse.createByErrorMessage("数据库不存在记录");
			}
	}
}
